<?php

namespace model;

use common\Model;
use common\Check;

class article extends Model
{
	private static $siteConfig;
	function __construct()
	{
		self::$siteConfig = new siteconfig();
	}

	//获取栏目数据并分页
	public function jsonPageSelect()
	{
		$db = $this->db();
		//根据标题搜索内容
		if (!empty($_GET['title']))
			$where['a.title LIKE'] = '%' . VarFilter($_GET['title']) . '%';

		//只搜索当前栏目内容
		if (isset($_GET['searchcid']))
			$newCid = $_GET['searchcid'] > 0 || $_GET['searchcid'] == 0 ? $_GET['searchcid'] : $_GET['cid'];
		else
			$newCid = $_GET['cid'];

		if ($newCid != 0)
			$where['a.cid'] = $newCid;

		//搜索 已审或草稿
		if (isset($_GET['stat']))
			$where['a.status'] = intval($_GET['stat']);

		//非超级管理员 只显示自己的内容
		if (LoginUserInfo('gid') != 1 && !SysRolCk('content_cate_all'))
			$where['a.uid'] = LoginUserInfo("userid");

		$p = intval($_GET['page'] ?? 0) ?: 1;
		$num = intval($_GET['limit'] ?? 0) ?: 15;

		$page = ['num' => $num, 'p' => $p, 'return' => true];

		$field  = 'b.id as cateid , b.name as catename,g.groupname,u.nickname ,a.id,a.cid,a.title,a.imgbl,a.attribute_a,a.attribute_b,a.attribute_c,a.status,a.time';
		$join[] = 'LEFT JOIN article_cate b ON a.cid=b.id';
		$join[] = 'LEFT JOIN admin_user u ON a.uid=u.id';
		$join[] = 'LEFT JOIN admin_group g ON u.gid=g.id';
		return [
			'data' => $db->table('article a')->field($field)->where($where)->join($join)->Page($page)->order('a.id DESC')->select(),
			'page' => $db->getPage()
		];
	}


	//信息统计查询
	public static function findCount()
	{
		$result = [];
		$pdo = \libs\pdo::Init();
		$prefix = $pdo->GetConfig();
		$fix = $prefix['prefix'];
		$cacheTime = self::$siteConfig->getCache();
		$cTime = $cacheTime['publishcachetime'];

		//每月全量分析统计
		$pdo->Cache($cTime);
		$data['meiyue'] = $pdo->QueryAll("SELECT COUNT(1) AS total, MONTH(`time`) AS months,SUM(case when status=1 then 1 else 0 end) as totalBJ FROM {$fix}article GROUP BY months asc;");
		//每周全量分析统计
		$pdo->Cache($cTime);
		$data['meizhou'] = $pdo->QueryAll("SELECT COUNT(1) AS total, WEEK(`time`) AS weeks,SUM(case when status=1 then 1 else 0 end) as totalBJ FROM {$fix}article  GROUP BY weeks asc;");
		//每年全量分析统计
		$pdo->Cache($cTime);
		$data['meinian'] = $pdo->QueryAll("SELECT COUNT(1) AS total, YEAR(`time`) AS years,SUM(case when status=1 then 1 else 0 end) as totalBJ FROM {$fix}article  GROUP BY years asc;");
		//每年按栏目分析统计
		$pdo->Cache($cTime);
		$data['catenian'] = $pdo->QueryAll("SELECT COUNT(1) AS value, a.cid AS cids,b.name AS name,b.color FROM {$fix}article a inner JOIN {$fix}article_cate b ON b.id=a.cid and b.ct=1 WHERE DATE_FORMAT(a.time,'%Y') = DATE_FORMAT(NOW(),'%Y') GROUP BY cids asc");
		//每月按栏目分析统计
		$pdo->Cache($cTime);
		$data['cateyue'] = $pdo->QueryAll("SELECT COUNT(1) AS value, a.cid AS cids,b.name AS name,b.color FROM {$fix}article a inner JOIN {$fix}article_cate b ON b.id=a.cid and b.ct=1 WHERE DATE_FORMAT(a.time,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m') GROUP BY cids asc");
		return $result['data'] = $data;
	}

	//关联查找一条数据
	public function findData()
	{
		$db = $this->db();
		$where['a.id'] = $_GET['id'];
		$join[] = 'LEFT JOIN article_content b ON a.id=b.aid';
		$result['content'] = $db->table('article a')->Join($join)->where($where)->find();

		//附件信息
		$attmentId = $result['content']['attid'];
		if (!empty($attmentId)) {
			$wheresAtt = "attid IN (" . $attmentId . ")";
			$result['attments'] = $db->table('attments')->where($wheresAtt)->Select();
		}

		return $result;
	}

	//添加数据
	public function insertData()
	{
		//插入数据信息部分
		$db = $this->db('article');
		$attid = empty($_POST['attid']) ? null : $_POST['attid'];
		$data = [
			'cid' => $_POST['cid'],
			'title' => VarFilter($_POST['title']),
			'attid' => $attid,
			'attribute_a' => $_POST['attribute_a'],
			'attribute_b' => $_POST['attribute_b'],
			'attribute_c' => $_POST['attribute_c'],
			'examine' => VarFilter($_POST['examine']),
			'img' => $_POST['img'],
			'imgbl' => empty($_POST['img']) ? 0 : 1,
			'time' => date('Y-m-d H:i:s', time()),
			'status' => $_POST['status'],
			'uid' => LoginUserInfo("userid"),
			'gid' => LoginUserInfo("gid"),
		];
		//验证数据
		$msg = Check::rule(
			array(check::len($data['mast']), '标题必须为3-200个字，请检查'),
			array(check::len($data['title'], 6, 400), '标题必须为3-200个字，请检查'),
			array(check::isChinese($data['examine']), '审核人必须为中文，请检查'),
			array(check::isImg($data['img']), '缩略图必须为有效图片路径，请检查')
		);
		if ($msg !== true)
			return  ['status' => 0, 'msg' => $msg];

		$re_key = $db->insert($data); //$this->error($db->getError());

		//根据主键插入内容部分
		if (!empty($_POST['content'])) {
			$db_content = $this->db('article_content');
			$data_content = [
				'content' => $_POST['content'],
				'aid' => $re_key,
			];
			$result_content = $db_content->insert($data_content);
		}

		if ($re_key > 0 || $result_content != 0) {
			SqlLog("添加内容ID:" . $re_key); //写入日志
			return ['status' => 1, 'msg' => '添加成功', 'cid' => $_POST['cid']];
		} else {
			return ['status' => 0, 'msg' => '数据错误！添加失败'];
		}
	}
	//关联更新数据
	public function updateData()
	{
		$db = $this->db();
		$attid = empty($_POST['attid']) ? null : $_POST['attid'];
		$data = [
			'cid' => $_POST['cid'],
			'title' => VarFilter($_POST['title']),
			'attid' => $attid,
			'attribute_a' => $_POST['attribute_a'],
			'attribute_b' => $_POST['attribute_b'],
			'attribute_c' => $_POST['attribute_c'],
			'examine' => VarFilter($_POST['examine']),
			'img' => $_POST['img'],
			'imgbl' => empty($_POST['img']) ? 0 : 1,
			//'time' => date('Y-m-d H:i:s', time()),
			'status' => $_POST['status'],
		];
		//验证数据
		$msg = Check::rule(
			array(check::len($_POST['mast']), '标题必须为3-200个字，请检查'),
			array(check::len($_POST['title'], 6, 400), '标题必须为3-200个字，请检查'),
			array(check::isChinese($_POST['examine']), '审核人必须为中文，请检查'),
			array(check::isImg($_POST['img']), '缩略图必须为有效图片路径，请检查')
		);
		if (!$msg) return ['status' => 0, 'msg' => $msg];

		$re_key = $db->table('article')->Where(['id' => $_POST['id']])->Update($data); //$this->error($db->getError());

		//存在修改，不存在插入
		if (!empty($_POST['content'])) {
			$db_content = $this->db('article_content');
			$data_content = [
				'content' => $_POST['content'],
				'aid' => $_POST['id'],
			];
			$result_content = $db_content->IfUpdate($data_content);
		}

		if ($re_key > 0 || $result_content != 0) {
			SqlLog("修改内容ID:" . $_POST['id']); //写入日志
			return ['key' => $re_key, 'status' => 1, 'msg' => '修改成功', 'cid' => $_POST['cid']];
		} else {
			return ['status' => 0, 'msg' => '数据没有变化！'];
		}
	}

	//关联删除一条或多条数据
	public function deleteData()
	{
		$aid = VarFilter($_POST['id']);
		$delid = explode(",", $aid);
		$db = $this->db();
		$tiao = 0;
		foreach ($delid as $contentId) {
			if (LoginUserInfo('gid') != 1)
				$where = ['a.id' => $contentId, 'a.uid' => LoginUserInfo("userid")];
			else
				$where = ['a.id' => $contentId];
			$join = 'LEFT JOIN article_content b ON a.id=b.aid';
			$tiao += $db->table('article a')->join($join)->where($where)->delete('a,b');
		}
		if (0 < $tiao) {
			SqlLog("删除内容ID:{$_POST['id']}");
			return true;
		} else {
			return false;
		}
	}

	//转移内容所在栏目	
	public function batchTransfer()
	{
		$pdo = \libs\pdo::Init();
		$prefix = $pdo->GetConfig();
		$fix = $prefix['prefix'];

		$aid = VarFilter($_POST['id']);
		$idAryy = explode(',', $aid);
		$transfercid = $_POST['transfercid'];

		$sql = "UPDATE {$fix}article SET ";
		$sql .= "cid = CASE id ";
		foreach ($idAryy as $vo) {
			$sql .= "WHEN $vo THEN '{$transfercid}' ";
		}
		$sql .= "END ";
		$sql .= "WHERE id IN ({$aid})";

		$re = $pdo->submit($sql);
		if (0 < $re)
			SqlLog("转移ID:{$aid}到cid为:{$transfercid}的栏目，成功{$re}条");
		return $re; //返回转移条数

	}
	//审核一条数据
	public function switchStatus()
	{
		$db = $this->db();
		$data = [$_POST['att'] => $_POST['status']];
		SqlLog("设置内容属性,ID:" . $_POST['id']); //写入日志
		return $db->table('article')->where(['id' => $_POST['id']])->Update($data);
	}
}
